/**
 * Project Name:javaBaseReview
 * Package Name:com.xuwei.base.tree
 * author:David
 * Date:2015年6月6日上午11:23:39
 * Copyright (c) 2015, xw123box@126.com All Rights Reserved.
 *
 */
package com.xuwei.base.tree;

import java.util.Arrays;

/**
 * @author David since 2015年6月6日 上午11:23:39
 * @version
 * @since JDK 1.6
 */
public class BTree2 {
    private BTree2 left;
    private BTree2 right;
    private int value;

    // private int num;

    public BTree2(int value) {
    	this.value = value;
    }

    public void add(int value) {
		if (value > this.value) {
		    if (right != null)
			right.add(value);
		    else {
			BTree2 bTree2 = new BTree2(value);
			right = bTree2;
		    }
		} else {
		    if (left != null)
			left.add(value);
		    else {
			BTree2 bTree2 = new BTree2(value);
			left = bTree2;
		    }
		}
    }

    public boolean find(int value) {
		if (value == this.value)
		    return true;
		else if (value > this.value) {
		    if (right == null)
			return false;
		    else
			return right.find(value);
		} else {
		    if (left == null)
			return false;
		    else
			return left.find(value);
		}

    }

    public void display() {
		System.out.println(value);
		if (left != null){
			left.display();
		}
		if (right != null){
		    right.display();
		}

    }

    /*
     * public Iterator iterator(){
     * 
     * }
     */

    public static void main(String[] args) {
		int[] values = new int[8];
		for (int i = 0; i < 8; i++) {
		    int num = (int) (Math.random() * 15);
		    // System.out.println(num);
		    // if(Arrays.binarySearch(values,num)<0)
		    if (!contains(values, num))
			values[i] = num;
		    else
			i--;
		}
	
		System.out.println(Arrays.toString(values));
	
		BTree2 root = new BTree2(values[0]);
		for (int i = 1; i < values.length; i++) {
		    root.add(values[i]);
		}
	
		System.out.println(root.find(13));
		root.display();
    }

    public static boolean contains(int[] arr, int value) {
		int i = 0;
		for (; i < arr.length; i++) {
		    if (arr[i] == value)
			return true;
		}
		return false;
    }

}
